﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Centny.PdfReader.Pdf;
using Centny.PdfReader.IO;
using Windows.Storage.Streams;
using Centny.PdfReader.Types;
using Centny.PdfReader.Security;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using PdfReader.Common;
using Centny.PdfReader.Render;
using CnyeCPlus.ExtSurface;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI;
using CnyeCPlus.FType;
using Centny.PdfReader.util;
using CnyeCPlus.util;
using System.Threading.Tasks;
// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace PdfReader
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class TestPage : PdfReader.Common.LayoutAwarePage
    {
        public TestPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private async void TestFontRender()
        {
            string filename = "ms-appx:///Assets/www.dat";
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(filename));
            if (file != null)
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
                Stream fs = stream.AsStream();
                byte[] bys = new byte[fs.Length];
                fs.Read(bys, 0, (int)fs.Length);
                FreeType ft = new FreeType(bys);
                ft.SetCharSize(100);
                PdfLexer.Beg();
                String ss = "";
                for (int k = 0; k < 100; k++)
                {
                    for (int i = 0; i < 256; i++)
                    {
                        Size s = ft.GenerateGlyph((char)i);
                        //if (s.Width > 0)
                        //{
                        //    ss += ((char)i + ":" + s.Width);
                        //}
                    }
                }
                PdfLexer.End("FontRender");
                System.Diagnostics.Debug.WriteLine(ss);
            }
        }
        private async void T1_Click_1(object sender, RoutedEventArgs e)
        {
            //this.TestFontRender();
            //if (true) return;
            //System.Diagnostics.Debug.WriteLine("Now:" + Timer.Now);
            //await Task.Delay(1000);
            //System.Diagnostics.Debug.WriteLine("Now:" + Timer.Now);
            //await Task.Delay(1000);
            //System.Diagnostics.Debug.WriteLine("Now:" + Timer.Now);
            //await Task.Delay(1000);
            PdfTimer t = new PdfTimer();
            System.Diagnostics.Debug.WriteLine("ssss");
            string filename = "ms-appx:///Assets/zlib.pdf";
            Uri baseUri = new Uri(filename);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(baseUri);
            //Application.Current.
            //PdfStreamLexer.RegisterOperatorExecuter(this.GetType().GetTypeInfo().Assembly);
            //RuntimeHelpers.RunClassConstructor(
            //PdfStreamLexer psl2 = new PdfStreamLexer(null, null);
            //Size
            //ESurfaceImageSource
            //BitmapImage;
            if (file != null)
            {
                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
                Stream fs = stream.AsStream();
                PdfLexer.Beg();
                PdfDocument doc = PdfDocument.Open(fs);
                //PdfTimer.SharedTimer.Beg();
                //PdfObject wobj = doc.RealObject(new PdfReference(179, 0, "obj"), PdfLexer.ObjectType.Long);
                //PdfTimer.SharedTimer.End("Widths");
                //foreach (long key in doc.Xref.Xrefs.Keys)
                //{
                //    if (key < 1)
                //    {
                //        continue;
                //    }
                //    doc.RealObject(new PdfReference(key, 0, "obj"));
                //}
                //PdfLexer.End("RealObject");
                //if (true) return;
                //
                //PdfStreamObject ts = doc.RealObject(new PdfReference(11, 0, "obj")) as PdfStreamObject;
                //Stream rs = ts.RStream(true);
                //byte[] bys = new byte[rs.Length];
                //rs.Read(bys, 0, (int)rs.Length);
                //ESurfaceImageSource sis = new ESurfaceImageSource(100, 100, true);
                //sis.CreateFBuilder(bys);
                //sis.SetFFontSize(30.0f);
                //Size csize=sis.FCharGlyphSize('B');
                //sis.BeginDraw();
                //sis.Clear(Colors.White);
                //sis.DrawFText('B', new Rect(0, 0, csize.Width, csize.Height), Colors.Black);
                //sis.EndDraw();
                //this.Img.Source = sis;
                //
                //PdfLexer.End("InitDocument");
                List<PdfObject> ap = doc.AllPages;
                //PdfLexer.End("AllPages");
                //TextBlock tb = new TextBlock();
                //tb.FontSize = 15;
                //tb.Text = "中国";
                //tb.Measure(new Size(500, 500));
                //Size ss = tb.DesiredSize;
                t.Beg();
                PdfClassObject pco = ap[0] as PdfClassObject;
                PdfImgSourcePage isp = new PdfImgSourcePage(pco, 4.0f);
                this.Img.Source = isp.ImgSource;
                //PdfTimer.SharedTimer.Total("Load");
                t.End("All");
                //System.Diagnostics.Debug.WriteLine("tval:" + Timer.SharedTimer.Total);
                //PdfStreamLexer psl = null;
                //foreach (PdfClassObject tco in ap)
                //{
                //    if (tco.Num == 1)
                //    {
                //        pco = tco;
                //    }
                //}
                //PdfDictionary dict = pco.InnerObj as PdfDictionary;
                //PdfReference pref = dict[PageKeys.Contents] as PdfReference;
                //PdfClassObject pco2 = doc.RealObject(pref) as PdfClassObject;
                //PdfArray ary = pco2.AsArray;
                //PdfReference pref2 = ary[0] as PdfReference;
                //PdfStreamObject pso = doc.RealObject(pref) as PdfStreamObject;
                //PdfStreamLexer psl = new PdfStreamLexer(pso.RStream(), pco);
                //psl.Process();
                //StreamReader sr = new StreamReader(pso.RStream());
                //String ss = sr.ReadToEnd();
                //System.Diagnostics.Debug.WriteLine(ss);
                //long ticks2 = PdfLexer.Timestamp();
                //System.Diagnostics.Debug.WriteLine("time:" + (ticks2 - ticks));
            }
        }

        public PdfStreamLexer Lexer
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void Execute(PdfOperator op)
        {
            throw new NotImplementedException();
        }


        public string Operator
        {
            get { throw new NotImplementedException(); }
        }
    }
}
